import {_decorator, Component, Label, find, Node} from 'cc';
import {ScoreViewModel} from "db://assets/Scripts/MVC/Score/ScoreViewModel";
import {ScoreUiState} from "db://assets/Scripts/MVC/Score/ScoreUiState";
import {EventManager} from "db://assets/Scripts/Common/EventManager";
import {EventType} from "db://assets/Scripts/Common/EventType";
import {AriPlane} from "db://assets/Scripts/Common/AriPlane";
import {NodePath} from "db://assets/Scripts/Common/NodePath";
import {PlayerController} from "db://assets/Scripts/MVC/Player/PlayerController";

const {ccclass, property} = _decorator;

/**
 * 分数Controller
 */
@ccclass('ScoreController')
export class ScoreController extends Component {
    /**
     * 分数ViewModel
     */
    public viewModel: ScoreViewModel = new ScoreViewModel();
    /**
     * 分数UiState
     */
    public uiState: ScoreUiState = this.viewModel.uiState;

    onLoad(){
        // 初始化Label组件
        this.uiState.label = this.getComponent(Label);
    }

    onEnable() {
        // 注册创建玩家事件
        EventManager.on(EventType.RESTART, this.onRestart, this);
        // 注册更新分数事件
        EventManager.on(EventType.UPDATE_SCORE, this.onUpdateScore, this);
    }

    onDisable() {
        // 取消注册创建玩家事件
        EventManager.off(EventType.RESTART, this.onRestart, this);
        // 取消注册更新分数事件
        EventManager.off(EventType.UPDATE_SCORE, this.onUpdateScore, this);
    }

    start() {

    }

    update(deltaTime: number) {

    }

    /**
     * 当创建玩家时
     */
    private onRestart() {
        this.uiState.playerNode = find(NodePath.PLAYER);
        this.uiState.playerController = this.uiState.playerNode.getComponent(PlayerController);
        this.onUpdateScore(0);
    }

    /**
     * 更新分数
     *
     * @param score 分数
     */
    private onUpdateScore(score: number) {
        // 当玩家不存在时
        if (!this.uiState.playerNode || !this.uiState.playerNode.active) {
            return;
        }

        // 累加分数
        this.uiState.playerController.uiState.score += score;
        // 设置分数
        this.uiState.label.string = `${this.uiState.playerController.uiState.score}`;

        // 记录全局分数
        AriPlane.SCORE = this.uiState.playerController.uiState.score;
    }
}